package risk.control.project.service;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import risk.control.project.framework.PostService;
import risk.control.project.utils.UUIDUtils;

import java.util.HashMap;

/**
 * 文件上传下载需要要的认证码
 */
@Service
public class AuthCodeService extends PostService {

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public AuthCodeService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }


    /**
     * 获取文件上传下载前置条件
     *
     * @return authCode
     */
    public String getAuthCode() {
        try (Jedis jedis = jedisPool.getResource()) {
            String authCode = UUIDUtils.generate();
            //设置保存时间为10秒
            jedis.setex("authCode_key_" + authCode, 10, authCode);
            HashMap<String, String> resMap = new HashMap<>();
            resMap.put("authCode", authCode);
            return generateSucceed(resMap);
        }
    }

    public HashMap<String, String> verifyAuthCode(String authCode) {
        HashMap<String, String> resMap = new HashMap<>();
        if (authCode == null || authCode.isEmpty()) {
            resMap.put("state", "001");
            resMap.put("msg", "authCode为空");
            return resMap;
        }
        String key = "authCode_key_" + authCode;
        try (Jedis jedis = jedisPool.getResource()) {
            //验证码
            boolean exists = jedis.exists(key);
            if (exists) {
                //说明有缓存
                String s = jedis.get(key);
                if (s.equals(authCode)) {
                    //验证码输入正确
                    resMap.put("state", "000");
                    resMap.put("msg", "authCode正确");
                } else {
                    //验证码输入错误
                    resMap.put("state", "002");
                    resMap.put("msg", "authCode错误");
                }
            } else {
                //验证码失效
                resMap.put("state", "003");
                resMap.put("msg", "authCode已失效");
            }
        }
        return resMap;
    }


}
